
import {isEmpty} from "../../../js/commonUtils";
import {createDownloadForm} from "../../../js/downloadUtils";
import actionUrls from "../../../../api/ApiUrls";
import Vue from "vue";

/**
 * 初始化
 * @param self
 * @param tiyData
 */
export const init = (self, tiyData,queryType) => {
  tiyData.tPage.total = 1;
  tiyData.tPage.startIndex = 0;
  tiyData.tPage.stepNumber = 40;
  tiyData.tPage.currentPage = 1;
  webList(self,tiyData,queryType);
};

export const showDeviceType = function (deviceType){
  let device = '其它';

  switch(deviceType){
    case 1:
      device = 'Android';
      break;
    case 2:
      device = 'IOS';
      break;
    case 3:
      device = 'PC';
      break;
    case 4:
      device = 'Mobile PC';
      break;
    default:
      break;
  }
  return device;
};

export const isFirstOrder = function (firstOrder){
  if(firstOrder==1){
    return '首单';
  }
  if(firstOrder==2){
    return '复购';
  }
  return '';
};

export const getShortNo= function (serialNumber){
  if(isEmpty(serialNumber)){
    return '';
  }
  if(serialNumber.length<=7){
    return serialNumber;
  }
  return serialNumber.substring(0,2)+'-'+serialNumber.substring(serialNumber.length-5,serialNumber.length);
};

//查询订单列表
export const webList = (self, tiyData,queryType) => {
  self.$Spin.show();
  self.$ySpliceAll(tiyData.tData.orderList);
  if(queryType==1){
    self.$ySpliceAll(tiyData.tParams.selectedOrders);
    self.isCheckedAllMessage=false;
  }
  //queryType: 1 新订单列表 2款项和安全确认
  let param = {
    "pageSize": tiyData.tPage.stepNumber,
    "pageNum": tiyData.tPage.currentPage,
    "queryType":queryType,
    "serialNumber": tiyData.tParams.orderSerialNumber,
    "state": tiyData.tParams.orderState,
    "userFullName": tiyData.tParams.userName,
    "startDate": tiyData.tParams.startTime,
    "endDate": tiyData.tParams.endTime,
    "waybill":tiyData.tParams.waybill,
    "withManageInfo": true,
    "queryAll": self.$authority(self.tRole.COMMON_1_100),
  };
  if(tiyData.tParams.startTime){
    param.startDate = Vue.prototype.$tiyQueryTime(new Date(tiyData.tParams.startTime).getTime());
  }
  if(tiyData.tParams.endTime){
    param.endDate = Vue.prototype.$tiyQueryTime(new Date(tiyData.tParams.endTime).getTime());
  }


  self.$apiNewOrder.orderList(param).then(function (response) {
    if(response.success){
      let orderPage = response.result;
      tiyData.tPage.total = orderPage.total;
      tiyData.tPage.stepNumber = orderPage.pageSize;
      orderPage.list.forEach(
        function (item) {
          tiyData.tData.orderList.push(item);
        }
      );
    }else{
      self.$Message.error(response.errorMessage);
    }
    self.$Spin.hide();
  });
};

/**
 * 导出EMS物流对接单
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const exportTransferExcel = (self, tiyData) => {
  let orders = createOrders(tiyData.tParams.selectedOrders);
  let data = {
    "orders": JSON.stringify(orders),
    "transferExcelType":tiyData.tParams.transferExcelType
  };
  self.$apiOrder.exportTransferExcel(data).then(function (response) {
    if (response.success) {
      let downloadForm = createDownloadForm(response.result, actionUrls.URL_DOWNLOAD_EXCEL);
      downloadForm.submit();
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};


/**
 * 订单备货
 * @param self
 * @param tiyData
 */
export const prepareOrders = (self, tiyData) => {
  self.$Spin.show();
  let orders = createOrders(tiyData.tParams.selectedOrders);
  self.$apiNewOrder.prepareOrders(orders).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.success('订单备货成功!');
      // //备货成功后下载采购单
      // let msgBody = {"id":response.result};
      // let downloadForm = createDownloadForm(msgBody, actionUrls.URL_ORDER_DOWNLOAD_PURCHASE_ORDER);
      // downloadForm.submit();
      webList(self, tiyData,1);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 导出订单报表
 * @param self
 * @param tiyData
 */
export const exportReport = (self, tiyData) => {
  let data = {"startDate": tiyData.tParams.startTime, "endDate":tiyData.tParams.endTime};
  if(tiyData.tParams.startTime){
    data.startDate = Vue.prototype.$tiyQueryTime(new Date(tiyData.tParams.startTime).getTime());
  }
  if(tiyData.tParams.endTime){
    data.endDate = Vue.prototype.$tiyQueryTime(new Date(tiyData.tParams.endTime).getTime());
  }
  self.$apiOrder.exportReport(data).then(function (response) {
    if (response.success) {
      let downloadForm = createDownloadForm(response.result, actionUrls.URL_DOWNLOAD_EXCEL);
      downloadForm.submit();
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};


/**
 * 清空已经选中的订单
 * @param self
 * @param tiyData
 */
export const clearSelectedOrders = (self, tiyData) => {
  self.isCheckedAllMessage=false;
  tiyData.tParams.selectedOrders = [];
}

/**
 * 订单出库
 * @param self
 * @param tiyData
 */
export const stockOutOrders = (self, tiyData) => {
  self.$Spin.show();
  let orders = createOrders(tiyData.tParams.selectedOrders);
  self.$apiNewOrder.stockOutOrders(orders).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.success('订单出库成功!');
      webList(self, tiyData,1);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 选中的订单构造传回后台的订单列表
 * @param selectedOrders
 */
function createOrders(selectedOrders) {
  let orders = [];
  selectedOrders.forEach(function (item) {
    let order = {};
    order.id = item.id;
    order.serialNumber = item.serialNumber;
    orders.push(order);
  });
  return orders;
}
/**
 * 请求下单用户联系信息
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const getUserContactInfo = (self, tiyData, userId) => {
  self.$Spin.show();
  self.$apiUser.getUserContactInfo({
    "userId": userId
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tStatus.modalUserContactInfo.isShow = true;
      var result = response.result;
      tiyData.tStatus.modalUserContactInfo.info.phoneCode = result.phoneCode;
      tiyData.tStatus.modalUserContactInfo.info.mobile = result.mobile;
      tiyData.tStatus.modalUserContactInfo.info.email = result.email;
      tiyData.tStatus.modalUserContactInfo.info.facebook = result.facebook;
      tiyData.tStatus.modalUserContactInfo.info.instagram = result.instagram;
      tiyData.tStatus.modalUserContactInfo.info.web = result.web;
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 批量导出配货单
 * @param self
 * @param tiyData
 */
export const batchExportOrdersBlank = (self, tiyData) => {
  let orders = [];
  tiyData.tParams.selectedOrders.forEach(function (item) {
    orders.push(item.id);
  });
  self.$apiOrder.exportOrderBlank({"ids": orders}).then(function (response) {
    if (response.success) {
      let msgBody = {"id":response.result};
      let downloadForm = createDownloadForm(msgBody, actionUrls.URL_ORDER_DOWNLOAD_ORDER_BLANK);
      downloadForm.submit();
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 批量导出发货单
 * @param self
 * @param tiyData
 */
export const batchExportOrdersInvoice = (self, tiyData) => {
  let orders = [];
  tiyData.tParams.selectedOrders.forEach(function (item) {
    orders.push(item.id);
  });
  self.$apiOrder.exportInvoice({"ids": orders}).then(function (response) {
    if (response.success) {
      let msgBody = {"id":response.result};
      let downloadForm = createDownloadForm(msgBody, actionUrls.URL_ORDER_DOWNLOAD_ORDER_INVOICE);
      downloadForm.submit();
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};


/**
 * 导出秒帐销售单
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const exportMiaozhangSale = (self, tiyData) => {
  let orders = [];
  tiyData.tParams.selectedOrders.forEach(function (item) {
    orders.push(item.id);
  });
  self.$apiOrder.exportMiaozhangSale({"ids": orders}).then(function (response) {
    if (response.success) {
      let downloadForm = createDownloadForm(response.result, actionUrls.URL_DOWNLOAD_EXCEL);
      downloadForm.submit();
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};


/**
 * 导出订单采购单
 * @param self
 * @param tiyData
 * @returns {Array}
 */
export const exportPurchaseOrders = (self, tiyData) => {
  let orders = createOrders(tiyData.tParams.selectedOrders);
  self.$apiOrder.exportPurchaseOrders(orders).then(function (response) {
    if (response.success) {
      //备货成功后下载采购单
      let msgBody = {"id":response.result};
      let downloadForm = createDownloadForm(msgBody, actionUrls.URL_ORDER_DOWNLOAD_PURCHASE_ORDER);
      downloadForm.submit();
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};


/**
 * 批量导出订单产品编码，用于打印
 * @param self
 * @param tiyData
 */
export const exportProductCodeForPrint = (self, tiyData) => {
  let orders = createOrders(tiyData.tParams.selectedOrders);
  self.$apiOrder.exportProductCodeForPrint(orders).then(function (response) {
    if (response.success) {
      //下载产品编码
      let msgBody = {"id":response.result};
      let downloadForm = createDownloadForm(msgBody, actionUrls.URL_ORDER_DOWNLOAD_PRODUCT_CODE);
      downloadForm.submit();
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 导出订单流水
 * @param self
 * @param tiyData
 */
export const exportOrderTurnover = (self, tiyData) => {
  let data = {"startDate": tiyData.tParams.startTime, "endDate":tiyData.tParams.endTime};
  if(tiyData.tParams.startTime){
    data.startDate = Vue.prototype.$tiyQueryTime(new Date(tiyData.tParams.startTime).getTime());
  }
  if(tiyData.tParams.endTime){
    data.endDate = Vue.prototype.$tiyQueryTime(new Date(tiyData.tParams.endTime).getTime());
  }
  self.$apiOrder.exportOrderTurnover(data).then(function (response) {
    if (response.success) {
      let downloadForm = createDownloadForm(response.result, actionUrls.URL_DOWNLOAD_EXCEL);
      downloadForm.submit();
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**修改重要说明
 * @param self
 * @param params {orderIds:[], importantNote:""}
 * */
export const modifyImportantNote = (self, tiyData) => {
  self.$Spin.show();
  self.$apiOrder.modifyImportantNote(tiyData.tParams.modifyImportantNote).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.success('修改重要说明成功!');
      tiyData.tStatus.modalImportantNote.isShow = false;
      webList(self, tiyData,1);
    } else {
      let error = "修改重要说明失败！";
      if(response.errorMessage){
        error += response.errorMessage;
      }
      self.$Message.error(error);
    }
  });
};

//导出跨境电商综合服务平台认证数据
export const exportTradeData = (tiyData, self) => {
  let orderIds = tiyData.tParams.selectedOrders.map(obj => {return obj.id});
  let params = {ids: orderIds};
  self.$Spin.show();
  self.$apiOrder.exportTradeData(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      let msgBody = {"id": response.result};
      let downloadForm = createDownloadForm(msgBody, actionUrls.URL_ORDER_DOWNLOAD_TRADE_DATA);
      downloadForm.submit();
    }else{
      console.error(response.errorMessage);
      self.$Message.error(response.errorMessage);
    }
  }).catch(() => {
    self.$Message.error("导出失败！");
    self.$Spin.hide();
  })
}
